import React, { useState, useEffect } from 'react';
import { Button, Divider } from 'antd';
import { useHistory } from 'react-router-dom';
import { LogoutOutlined, HomeOutlined, LoadingOutlined, RollbackOutlined } from '@ant-design/icons';
import {
  openNotification_util, checkdatavalid_util_formdata, fetchsync_util,
  resultdata_to_formdata, addkey_for_mxdata,
  use_dict_byzdmc,
  convertISODateTimeToYYYYMMDDHHMMSS,
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { SaveOutlined } from '@ant-design/icons';
import logo from '../../../img/shipSRM/chlogo.png'
import { use_tzgg_initformdata, use_tzgg_initformdata_view } from './use_sys_config.js';
moment.locale('zh-cn')
var storage = window.localStorage;
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route';

const Tzgg_form = () => {
  const history = useHistory();
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    dict_xxlx: [],
  })

  //主表数据
  const [formdata, setformdata] = useState(JSON.parse(storage.pre_tzgg_item).type != "view" ? use_tzgg_initformdata : use_tzgg_initformdata_view)
  const { nowroute, setnowroute, collapsed, setcollapsed } = useStore();

  const init = async () => {
    var dictObj = await use_dict_byzdmc(["dict_xxlx"])
    dynDatasObject.dict_xxlx = dictObj.dict_xxlx
    setdynDatasObject({ ...dynDatasObject })
  }

  //加载主表数据
  const loadformdata = async (id) => {
    let rtdata = await fetchsync_util("/admin/sys/query_tzgg_byid", 'POST', { id: id }, "json")
    let newformdata = rtdata.resultdata.formdata
    newformdata.create_time = newformdata.create_time ? convertISODateTimeToYYYYMMDDHHMMSS(newformdata.create_time) : ""
    newformdata.update_time = newformdata.update_time ? convertISODateTimeToYYYYMMDDHHMMSS(newformdata.update_time) : ""
    newformdata.fbsj = newformdata.fbsj ? convertISODateTimeToYYYYMMDDHHMMSS(newformdata.fbsj) : ""
    setformdata({ ...formdata, ...resultdata_to_formdata(newformdata, formdata) });
  }

  // 页面进入加载数据
  useEffect(() => {
    if (JSON.parse(storage.pre_tzgg_item).type == "edit") {
      loadformdata(JSON.parse(storage.pre_tzgg_item).data.id)
      init()
    }
    else if (JSON.parse(storage.pre_tzgg_item).type == "add") {
      init()
    }
    else {
      loadformdata(JSON.parse(storage.pre_tzgg_item).data.id)
    }
  }, [])

  //设置value
  const setfield = (onekey, value, settype) => {
    if (settype == 'single') {
      var newitem = formdata[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
      setformdata(newformdata)
    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }


  const handleupload = async () => {


    var checkobj = checkdatavalid_util_formdata(formdata)
    //主表字段校验没通过不能保存，目前没写子表校验。

    if (!checkobj.rtstatus) { openNotification_util(checkobj.rtmessage); return; }
    else;
    //设置submit url
    var uploadurl = "";


    if (JSON.parse(storage.pre_tzgg_item).type == "add" ||
      JSON.parse(storage.pre_tzgg_item).type == "copy") {
      uploadurl = "/admin/sys/add_tzgg"
    }
    else if (JSON.parse(storage.pre_tzgg_item).type == "edit") {
      uploadurl = "/admin/sys/update_tzgg"

    }
    else;
    let newformdata = formdata;
    newformdata.tznr.value = JSON.parse(storage.tinymce_content);
    let rtdata = await fetchsync_util(uploadurl, 'POST', { formdata: newformdata }, "json")
    rtdata.rtstatus ? openNotification_util(rtdata.rtmessage) : 1
    setformdata(rtdata.resultdata.formdata);
    dropByCacheKey("tzgg_form")
    dropByCacheKey("tzgg_list")

    setnowroute({ route: "/shipSRM/sys/tzgg_list", title: "通知公告", closeroute: "/shipSRM/sys/tzgg_form" })

  }



  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "5.9vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem"
    }}
    data-page-type="form">

      <div style={{width:"100%",height:"100%",backgroundColor:"white",overflow:"auto"}}>
      <div style={{
        width: "100%", height: "7%", position: "sticky", top: "1%", backgroundColor: "white", color: "black", display: "flex",
        zIndex: 105, borderBottom: "2px solid #a91f24"
      }}>

        <div style={{ width: "40%", textAlign: "left", paddingRight: "1rem", display: "flex", alignItems: "center", fontWeight: "600" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          工具栏
        </div>
        {JSON.parse(storage.pre_tzgg_item).type != "view" ?
          <div style={{ width: "60%", textAlign: "right", paddingRight: "1rem" }}>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <Button type="primary" onClick={handleupload}
              style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.2rem" }}>
              <SaveOutlined />{JSON.parse(storage.pre_tzgg_item).type == "add" ? "保存" : "修改"}</Button>
          </div>
          :
          <></>
        }
      </div>

      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "98%", marginLeft: "1%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {renderfileditem()}
        </div>
        {/* 主表区域结束 */}
      </div>
      </div>
    </div>
  )
}


export default Tzgg_form

var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `white`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1vw", paddingRight: "1vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1vw", height: "2vw", position: "absolute", right: "6.5%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
  butbackstyle: { borderRadius: "0.4rem", backgroundColor: "#a91f24", height: "2vw", position: "absolute", right: "12%", top: "0%", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  kshcontainer: {
    width: "98%", position: "relative", backgroundColor: "white", color: "#666",
    borderRadius: "10px", paddingBottom: "2rem", overflow: "visible"
  },
}
